/*
 * @Description: 拼团商品详情
 * @version: 1.0.0
 * @Company: ZMT
 * @Port: 熊健
 * @Author: XU BING
 * @Date: 2018-10-27 11:00:32
 * @LastEditors: XU BING
 * @LastEditTime: 2018-11-22 17:01:37
 */
var flag = true;
var isOut = "";
var dataInfo = new Object(),

  template = {
    loadData: function () { // template.loadData();

      ajaxTemplate(addressTest + SERVICE.queryGoodsDetail, function (data) {
        if (data.tag == 0) {
          var daTa = data.data.result[0];
          if (dataInfo.all.isFx == 1 && (daTa.role > 2)) {
            //dataInfo.all.isDz = true; H5商城无店主佣金显示 所以注释
            dataInfo.all.priceRange = daTa.priceRange;
            dataInfo.all.priceRangeAmount = daTa.priceRangeAmount;
            dataInfo.all.inventory = daTa.inventory;
            dataInfo.all.killInventory = daTa.killInventory;
          };
          dataInfo.all.killpriceRange = daTa.killpriceRange;
          dataInfo.all.killpriceRangeAmount = daTa.killpriceRangeAmount;
          dataInfo.all.limitNumber = daTa.limitNumber;
          dataInfo.all.secondKillPrice = daTa.secondKillPrice;
          dataInfo.all.isCoupons = daTa.isCoupons;
          dataInfo.all.freeShippingAmount = daTa.freeShippingAmount;
          dataInfo.all.shippingAmount = daTa.shippingAmount;
          dataInfo.all.sellingPointsDesc = daTa.sellingPointsDesc; // 卖点
          dataInfo.all.lowMarketPrice = daTa.lowMarketPrice; //市场价
          dataInfo.all.lowSellingPrice = daTa.lowSellingPrice; //售价
          dataInfo.all.lowVipPrice = daTa.lowVipPrice; //会员价
          dataInfo.all.imgUrl = daTa.imgUrl; //   商品图片
          dataInfo.all.goodsName = daTa.goodsName; //商品名字
          dataInfo.all.virtualGoodsCode = daTa.virtualGoodsCode; //   商品编码

          /*详情+购买须知 图片处理*/
          daTa.detail = template.imgReduce(daTa.detail, '.jpg');
          daTa.detail = template.imgReduce(daTa.detail, '.png');
          daTa.instructions = template.imgReduce(daTa.instructions, '.jpg');
          daTa.instructions = template.imgReduce(daTa.instructions, '.png');
          //新增视频播放
          dataInfo.all.videoUrl = daTa.videoUrl; //   商品图片预览
          dataInfo.all.videoFristImgUrl = daTa.videoFristImgUrl; //   商品图片预览
          setTimeout(function () {
            dataInfo.all.instructions = daTa.instructions; //   购买须知
            dataInfo.all.detail = daTa.detail; //商品详情
            dataInfo.all.datailImgs = template.getImgUrl(dataInfo.all.detail); //商品详情图片优化

          }, 400);
          /*详情+购买须知 图片处理*/
        } else {
          template.hintInfo(data.errMsg);


        };
      }, {
        virtualGoodsCode: dataInfo.productId,

      }, true);

    },
    getImgUrl: function (str) { //获取商品详情图片集合 template.getImgUrl(str);
      var arr = new Array();
      str.split('src="').forEach(function (item, index) {
        index > 0 ? arr.push(item.split('"')[0] + "_600x8000.jpg") : '';
      });
      return arr;
    },
    imgReduce: function (imgData, format) { //格式前面要加.，降低容错率    template.imgReduce(imgData, format);
      var imgArr = imgData.split(format),
        imgStr = '';
      imgArr.forEach(function (item, index) {
        if (index == imgArr.length - 1 || imgArr[index].indexOf('group1/M00') < 0) {
          imgStr += imgArr[index];
        } else {
          format == '.jpg' ? imgStr += imgArr[index] + '.jpg_600x8000.jpg' : imgStr += imgArr[index] + '.png_600x8000.jpg';
        };
      });
      return imgStr;

    },

    init: function () { // template.init();
      dataInfo.scrollswitch = 1;
      dataInfo.switchTop = 1;
      dataInfo.productId = getQueryString('productId');
      dataInfo.userId = getQueryString('userId');
      dataInfo.myVideo = document.getElementsByClassName('theVideo')[0];
      Vue.use(VueLazyload, {
        preLoad: 2.4,
        error: '../img/product/init.png',
        loading: '../img/product/init.png',
        attempt: 2
      });
      dataInfo.all = new Vue({
        el: ".body-fake",
        data: {
          versions: versions,
          ChooceSaveType: 0, //默认加入购物车保存
          isFx: getQueryString('isFx'), //分销展示判断
          isDz: false, //是否分销店主 - 显示商品赚多少钱
          playVideoUrl: '../share/img/playVideo2.png', //暂停
          statusMs: '开始', //开始结束 切换
          limitNumber: '', //限购数量
          secondKillPrice: "", //秒杀价格
          scrollNum: 1, //当前滑动到第几页
          scrollAll: 1, //可滑动的总页数
          imgUrl: [], //滑动图片汇总
          videoUrl: '', //视频地址
          videoFristImgUrl: '', //视频首图
          dataBtn: '商品<br/>详情', //商品详情按钮
          isCoupons: "", //是否有店铺优惠券
          msType: '', //是否是秒杀 整体开关控制
          playVideo: true, //视频播放与否 false代表播放 页面预览图消失
          detail: '', //商品详情
          instructions: '', //购买须知
          backtop: false, //返回顶部按钮显隐
          freeShippingAmount: "", //满多少钱包邮
          shippingAmount: "", //邮费
          goodsName: '', //商品名称
          sellingPointsDesc: '', //商品描述
          lowSellingPrice: '',
          lowMarketPrice: '',
          lowVipPrice: '',
          priceRange: '', //价格的区间-fx
          priceRangeAmount: '', //佣金的区间-fx
          inventory: '', //分销库存
          killInventory: '', //秒杀库存
          virtualGoodsCode: '', //商品id
          hot: [], //热卖商品、推荐商品集合
          diary: [], //推荐日记
          versions: getQueryString('versions'), //版本号
          versionsCode: getQueryString('versionsCode'), //版本号
          days: '00', //秒杀倒计时
          hours: '00',
          minutes: '00',
          seconds: '00',
          queryShopCodeData: {}, //查询店主邀请码
          CartNum: 0, //购物车数量
          bottowPopup: { //底部弹框
            cartShow: false, //规格选择
            show: false, //保障说明
          },
          specificationData: { //购物车规格
            inventory: "",
            specificationList: [],
            secondActive: 100,
            specificationDetail: {}, //规格详情
            num: 1, //数量
            goodsCode: "",
            id: ""
          },
          PTdata: { //拼团数据
            PTinfo: {},
            GroupList: []
          },
          type: 1, //判断流程图
          ptShow: false, //正在拼单
          isApp: "", //判端APP
          isXiangou: false, //是否限购
          noLogin: "", //判断是否等路
          datailImgs: [], //商品详情图片优化
          isJoin: '', //是否是参团 ‘T’ 是 ‘F’否
          PTnumStyle: "PTnumStyle",
          
        },
        methods: {
          onChange: function (index) { //轮播指示回显
            this.scrollNum = index + 1;
          },
          init: function () {         
            //  dataInfo.all.specificationChooce(false) //规格
            dataInfo.all.PTgetMainPD()
            if (getQueryString('isApp') == 1) {
              dataInfo.all.isApp = true;
              dataInfo.all.noLogin = {
                noLogin: 1
              }
              $(".product-details-hot-false").css("padding-bottom", "0px")
            } else {
              dataInfo.all.isApp = 0;
              dataInfo.all.noLogin = false;
            }
          },
          sheng: function (num) { //省钱判断

            if (num < 0) {
              return "省0元"
            } else {
              
              if(num){
                return "省" + num + "元"
              }else{
                return "省**元"
              }
              
            }

          },
          PtRule: function (type) { //拼团规则

            if (dataInfo.all.isApp==0) {
              location.href = 'PtRule.html?type=' + type
            } else {
              location.href = "jg://com.simeitol.www?type=PtRule&" + type
            }
          },
          on: function () {
            downAppFun();
          },
          PTgetMainPD: function () { //获取拼团产品详情-拼团价
            ajaxTemplate(addressTest + SERVICE.PTgetMainPD, function (data) {
              if (data.tag == 0) {
                dataInfo.all.PTdata.PTinfo = data.data.result.PDinfo;
                dataInfo.all.PTdata.GroupList = data.data.result.GroupList
                //下架跳转下架页面
                data.data.result.isOut == 1 ? location.href = "../html/soldOut.html" : '';
                dataInfo.all.countdown()
              } else {
                dataInfo.all.$toast(data.errMsg);
                dataInfo.all.PTdata.PTinfo.activityPrice="**"

              };
            }, {
              virtualgoodsID: getQueryString("productId"),
              activityId: getQueryString("activityId"),
            }, true);
          },
          specificationChooce: function (tg, type, isJoin) { //规格选择
            dataInfo.all.isJoin = isJoin
            dataInfo.all.ChooceSaveType = type
            dataInfo.all.specificationData.secondActive = 100
            if (!!access_token) {
              
              ajaxTemplate(addressTest + SERVICE.PTgetsubPDinfo, function (data) {
                if (data.tag == 0) {
                  if (tg) {
                    dataInfo.all.bottowPopup.cartShow = !dataInfo.all.bottowPopup.cartShow;
                  }
                  dataInfo.all.specificationData.specificationList = data.data.result.goodlist
                  dataInfo.all.specificationData.inventory = data.data.result.stock
                  dataInfo.all.specificationData.num = 1
                  dataInfo.all.specificationData.specificationDetail.imgUrl = dataInfo.all.imgUrl;
                  dataInfo.all.specificationData.specificationDetail.activityPrice = data.data.result.priceRange
                  dataInfo.all.specificationData.specificationDetail.oldPrice = data.data.result.oldPrice;
                  dataInfo.all.specificationData.specificationDetail.specifications = "请选择规格"
                  if (dataInfo.all.specificationData.specificationList.length == 1 && dataInfo.all.specificationData.specificationList[0].activityInventory != 0) {
                    dataInfo.all.specificationData.secondActive = 0;
                    dataInfo.all.specificationData.goodsCode = dataInfo.all.specificationData.specificationList[0].goodsCode
                    dataInfo.all.specificationData.specificationDetail = dataInfo.all.specificationData.specificationList[0]
                    dataInfo.all.specificationData.inventory = dataInfo.all.specificationData.specificationList[0].activityInventory
                    if (dataInfo.all.specificationData.specificationList[0].islimitOne == 1) {
                      dataInfo.all.isXiangou = true;
                      dataInfo.all.specificationData.num = 1
                    } else {
                      dataInfo.all.isXiangou = false
                    }
                  } else {

                    if (dataInfo.all.specificationData.specificationList[0].activityInventory != 0) {
                      dataInfo.all.specificationData.secondActive = 0;
                    }
                    dataInfo.all.specificationData.goodsCode = dataInfo.all.specificationData.specificationList[0].goodsCode
                    dataInfo.all.specificationData.specificationDetail = dataInfo.all.specificationData.specificationList[0]
                    dataInfo.all.specificationData.inventory = dataInfo.all.specificationData.specificationList[0].activityInventory
                    if (dataInfo.all.specificationData.specificationList[0].islimitOne == 1) {
                      dataInfo.all.isXiangou = true;
                      dataInfo.all.specificationData.num = 1
                    } else {
                      dataInfo.all.isXiangou = false
                    }
                  }
                } else {
                  dataInfo.all.bottowPopup.cartShow = false
                  dataInfo.all.$toast(data.errMsg);
                  


                }
              }, {
                virtualgoodsID: getQueryString("productId"),
                activityId: getQueryString("activityId")
              }, dataInfo.all.noLogin);

            } else {
              jumpLogin()
            }
          },
          specificationDetailC: function (index) { //规格详情
            dataInfo.all.specificationData.secondActive = index
            if (dataInfo.all.specificationData.specificationList[index].islimitOne == 1) {
              dataInfo.all.isXiangou = true;
              dataInfo.all.specificationData.num = 1

            } else {
              dataInfo.all.isXiangou = false
            }
            dataInfo.all.specificationData.inventory = dataInfo.all.specificationData.specificationList[index].activityInventory
            dataInfo.all.specificationData.specificationDetail = dataInfo.all.specificationData.specificationList[index]
            dataInfo.all.specificationData.id = dataInfo.all.specificationData.specificationList[index].id
            dataInfo.all.specificationData.goodsCode = dataInfo.all.specificationData.specificationList[index].goodsCode
          },

          specificationChooceSave: function () { //规格选择确定
            if (flag) {
              if (dataInfo.all.specificationData.specificationList.length != 1 && dataInfo.all.specificationData.secondActive == 100) {
                dataInfo.all.$toast('请选择规格');
              } else {
                flag = false
                //立即购买
                var goodsInfo = new Object();
                goodsInfo.num = dataInfo.all.specificationData.num;
                goodsInfo.goodsCode = dataInfo.all.specificationData.goodsCode;
                goodsInfo.isKill = 1;
                // escape()
                var result = JSON.stringify(goodsInfo);
                if (!!access_token) {

                  ajaxTemplate(addressTest + SERVICE.PTVerification, function (data) {
                    flag = true
                    if (data.tag == 0) {
                      if (data.data.result.isJoin == 0) {

                        dataInfo.all.$toast(data.data.result.reason);
                      } else {
                        setTimeout(function () {
                          if (dataInfo.all.isJoin == "F") {
                            window.location.href = 'orderFilling.html?orderData=' + result + '&grouponGoodsVirtualId=' + dataInfo.all.PTdata.PTinfo.id + '&activityId=' + getQueryString("activityId") + '&isJoin=' + dataInfo.all.isJoin + '&grouponGoodsItemId=' + dataInfo.all.specificationData.specificationDetail.id
                          } else {
                            window.location.href = 'orderFilling.html?orderData=' + result + '&grouponGoodsVirtualId=' + dataInfo.all.PTdata.PTinfo.id + '&activityId=' + getQueryString("activityId") + '&isJoin=' + dataInfo.all.isJoin + '&grouponGoodsItemId=' + dataInfo.all.specificationData.specificationDetail.id + '&groupId=' + dataInfo.all.groupId
                          }

                        }, 500)
                      }
                    } else {};
                  }, {
                    userid: userId,
                    activityId: getQueryString("activityId"),
                    isJoinGroup: dataInfo.all.isJoin
                  });
                } else {
                  jumpLogin()

                }
              }
            } else {
              dataInfo.all.$toast("重复点击");
            }
          },
          countdown() {
            if (dataInfo.all.PTdata.GroupList.length == 0) {

            } else {

              var timer = setInterval(function () {
                for (var i = 0; i < dataInfo.all.PTdata.GroupList.length; i++) {
                  // let remainTime = dataInfo.all.PTdata.GroupList[i].endTime - dataInfo.all.PTdata.GroupList[i].currentTime
                  var remainTime = dataInfo.all.PTdata.GroupList[i].endTime - Date.parse(new Date())
                  dataInfo.all.PTdata.GroupList[i].remainTime = remainTime

                  var t = dataInfo.all.PTdata.GroupList[i].remainTime;

                  if (t > 0) {
                    var day = Math.floor(t / 86400000)
                    var hour = Math.floor((t / 3600000) % 24)
                    var min = Math.floor((t / 60000) % 60)
                    var sec = Math.floor((t / 1000) % 60)
                    day = day < 10 ? '0' + day : day
                    hour = hour < 10 ? '0' + hour : hour
                    min = min < 10 ? '0' + min : min
                    sec = sec < 10 ? '0' + sec : sec
                    var format = ''
                    format = hour + ":" + min + ":" + sec
                    dataInfo.all.PTdata.GroupList[i].remainTimeStr = format

                    $("#time" + i).html(dataInfo.all.PTdata.GroupList[i].remainTimeStr)
                    $("#ptime" + i).html(dataInfo.all.PTdata.GroupList[i].remainTimeStr)
                  } else {
                    // 进行判断 如果数据内所有的倒计时已经结束，那么结束定时器， 如果没有那么继续执行定时器
                    var flag = dataInfo.all.PTdata.GroupList.every((val, ind) => val.remainTime <= 0)
                    if (flag) clearInterval(timer)

                    dataInfo.all.PTdata.GroupList[i].remainTimeStr = "00:00:00"
                    $("#time" + i).html("00:00:00")
                    $("#ptime" + i).html("00:00:00")
                  }
                }
              }, 1000)
            }
          },
          jumpSwiper: function (e) {
            if (!!this.videoUrl) { //有视频条件下 可点击
              if (e == 1 && this.scrollNum == 1) { //点击图片
                dataInfo.swiper.slideTo(1, 500, false);
                this.scrollNum = 2;
              } else if (e == 0) { //点击视频
                dataInfo.swiper.slideTo(0, 500, false);
                this.scrollNum = 1;
              };
            };
          },
          back_top: function () {
            $(".storeBody").stop().animate({
              "scrollTop": 0
            }, 500);
          },
          handleScroll: function () {
            var storeBody = document.getElementsByClassName('storeBody')[0],
              scrollTop = storeBody.pageYOffset || storeBody.scrollTop;
            if (scrollTop > 300) {
              this.backtop = true;
            } else {
              this.backtop = false;
            };
          },
          directPT: function (groupId) { //直接拼
            
            if (dataInfo.all.isApp==0) {
              dataInfo.all.groupId = groupId
              dataInfo.all.specificationChooce(true, 1, "T")
            } else {
              location.href = "jg://com.simeitol.www?type=directPT&" + groupId
            }
          },
          toDetails: function () {
            $(".storeBody").stop().animate({
              "scrollTop": $(".toDetails").get(0).offsetTop
            }, 400);
          },
          toCoupon: function (num) { //保障说明
            if (dataInfo.all.isApp==0) {
              dataInfo.all.bottowPopup.show = !dataInfo.all.bottowPopup.show;
            } else {
              location.href = "jg://com.simeitol.www?type=toCoupon"
            }

          },
          ptShowBtn: function () { //正在拼团
            if (dataInfo.all.isApp==0) {
              dataInfo.all.ptShow = !dataInfo.all.ptShow
            } else {
              location.href = "jg://com.simeitol.www?type=ptShowBtn"
            }
          },
          toProduct: function (code, imgUrl, title, isSelf) { //热卖商品
            dataInfo.scrollswitch == 1 ? location.href = "../html/productDetails.html?userId=" + userId + "&access_token=" + token + "&productId=" + code + "&shareUrl=" + imgUrl + "&shareTitle=" + title + '&isFx=' + getQueryString('isFx') + "&v_=" + getQueryString('v_') + "&pt_=" + getQueryString('pt_') + "&m_=" + getQueryString('m_') + "&uid_=" + getQueryString('uid_') + "&access_token=" + getQueryString('access_token') : '';
          },
          toDiary: function (id, createTime, userId) { //日记详情
            location.href = "jg://com.simeitol.www?type=toDiary&id=" + id + "&createTime=" + createTime + "&userId=" + userId + "&goodsCode=" + dataInfo.all.virtualGoodsCode;
          },
          toMoreDiary: function () { //更多日记
            location.href = "jg://com.simeitol.www?type=toMoreDiary&userId=" + userId + "&productId=" + this.virtualGoodsCode;
          },
          playVideoNow: function () {
            this.playVideo = false;
            dataInfo.myVideo = document.getElementsByClassName('theVideo')[0]; //二次定义 不然会报错
            dataInfo.progressWrap = document.getElementsByClassName('progressWrap')[0];
            dataInfo.playProgress = document.getElementsByClassName('playProgress')[0];
            dataInfo.progressFlag = setInterval(function () {
              var percent = dataInfo.myVideo.currentTime / dataInfo.myVideo.duration;
              dataInfo.playProgress.style.width = percent * (dataInfo.progressWrap.offsetWidth) + "px";
            }, 60);
            dataInfo.myVideo.addEventListener('ended', function () {
              dataInfo.all.playVideo = true;
              dataInfo.playProgress.style.width = 0;
              clearInterval(dataInfo.progressFlag);
            }, false);
            dataInfo.myVideo.play();
          },
          stopVideoNow: function () {
            dataInfo.myVideo = document.getElementsByClassName('theVideo')[0]; //二次定义 不然会报错
            if (dataInfo.myVideo.paused) {
              this.playVideoUrl = '../share/img/playVideo2.png';
              this.playVideoNow();
            } else {
              this.playVideoUrl = '../share/img/playVideo.png';
              dataInfo.myVideo.pause();
              clearInterval(dataInfo.progressFlag);
            }
          },
        },
        mounted: function () {
          /*返回顶部监控*/
          document.getElementsByClassName('storeBody')[0].addEventListener('scroll', this.handleScroll);
        },
        computed: {
          diaryWidth: function () {
            return this.diary.length * 155 + 5;
          },
          android: function () {
            if (browser.versions.android == true) {
              return false;
            } else {
              return true;
            }
          }
        }
      });
      dataInfo.all.init()
      template.loadData();
    },
    hintInfo: function (info) { // template.hintInfo();
      $(".hintInfo").html(info).show();
      setTimeout(function () {
        $(".hintInfo").fadeOut();
      }, 2500);
    },
    randomRecommendGoods: function () { // template.randomRecommendGoods();
      ajaxTemplate(!!getQueryString('isFx') ? addressUrl + SERVICE.queryFxGoodsRecommend : addressTest + SERVICE.randomRecommendGoods, function (data) {
        console.log(data);
        var daTa = data.data.result;
        if (data.tag == 0) {
          //  随机推荐商品
          dataInfo.all.hot = new Array();
          daTa.forEach(function (item, index) {
            if (item.isKill !== 0) {
              dataInfo.all.hot.push(item);
            };
          });
          setTimeout(function () {
            var tid = "index" + (daTa.length - 1);
            $('#' + tid).ready(function () {
              $(".loadImgBox").addClass("rgba").hide();
            });
          }, 300);
        } else {
          template.hintInfo(data.errMsg);
        };
      }, {
        virtualGoodsCode: dataInfo.productId
      });
    },
    getShareInfo: function () { // template.getShareInfo();
      var getShareInfo = "productId=" + dataInfo.productId + "&shareUrl=" + dataInfo.all.imgUrl[0] + "&shareTitle=" + dataInfo.all.goodsName;
      return getShareInfo;
    },
    toMall: function () { // template.toMall();
      dataInfo.scrollswitch = 2;
      dataInfo.switchTop == 1 ? dataInfo.switchTop = $(".toMall").get(0).offsetTop : '';
      $(".storeBody").stop().animate({
        "scrollTop": dataInfo.switchTop
      }, 400, function () {
        dataInfo.scrollswitch = 1;
      });
    },

  };
template.init();